package com.bml.architect.gateway.sentinel;

import com.alibaba.cloud.sentinel.datasource.RuleType;
import com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.nacos.api.config.ConfigService;

/**
 * @author: baiml
 * @Title: NacosWriteDataSource
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description:
 * @date: 2021/5/8 13:37
 */
public class NacosWriteDataSource<T> implements WritableDataSource<T> {



    private WriteDataSourceWrapper<T> wrapper;


    public NacosWriteDataSource(WriteDataSourceWrapper<T> wrapper){
        this.wrapper = wrapper;
    }

    @Override
    public void write(T t) throws Exception {
        synchronized (wrapper) {

            NacosDataSourceProperties nacos = wrapper.getNacosDataSourceProperties();
            String dataId = nacos.getDataId();
            String groupId = nacos.getGroupId();
            String dataType = nacos.getDataType();
            RuleType ruleType = nacos.getRuleType();
            Converter<T, String> configEncoder = wrapper.getConfigEncoder();
            String content = configEncoder.convert(t);
            ConfigService configService = wrapper.getConfigService();
            //发布到配置中心，发布的默认是json格式
            configService.publishConfig(dataId,groupId,content, nacos.getDataType());
        }
    }

    @Override
    public void close() throws Exception {

    }



}
